package com.lyncs.ods.utils;

import java.util.Objects;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author alex
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static Integer envType;

    public SpringUtils() {
    }

    public static boolean isDebug() {
        return Objects.equals(0, envType);
    }

    public static boolean isTest() {
        return Objects.equals(1, envType);
    }

    public static boolean isProd() {
        return Objects.equals(2, envType);
    }

    public static void setProduct() {
        envType = 2;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }

        Environment env = applicationContext.getEnvironment();
        String[] envActiveProfiles = env.getActiveProfiles();
        if (null == envType) {
            String[] var4 = envActiveProfiles;
            int var5 = envActiveProfiles.length;

            for (int var6 = 0; var6 < var5; ++var6) {
                String profile = var4[var6];
                if ("dev".equals(profile)) {
                    envType = 0;
                    break;
                }

                if ("test".equals(profile)) {
                    envType = 1;
                    break;
                }

                if ("prod".equals(profile)) {
                    envType = 2;
                    break;
                }
            }
        }

    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
